package my.spring.transaction;

import my.spring.transaction.definition.TransactionDefinition;
import my.spring.transaction.status.DefaultTransactionStatus;
import my.spring.transaction.status.TransactionStatus;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author fengbo
 * @date 2018/7/4
 */
public class JdbcTransactionManager implements PlatformTransactionManager {

    private DataSource dataSource;

    public JdbcTransactionManager(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public TransactionStatus getTransaction(TransactionDefinition definition) {
        Connection conn;
        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);
            TransactionResourceManager.bindResource(conn);
            return new DefaultTransactionStatus(conn, true, true, false);
        } catch (SQLException e) {
            throw new RuntimeException("Can not get connection for transaction!", e);
        }
    }

    @Override
    public void commit(TransactionStatus status) {
        Connection conn = (Connection) TransactionResourceManager.unbindResource();
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException("Commit failed with SQLException", e);
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                // 记录日志，但通常不会有进一步的有效处理
            }
        }
    }

    @Override
    public void rollback(TransactionStatus status) {
        Connection conn = (Connection) TransactionResourceManager.unbindResource();
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException("Rollback failed with SQLException!", e);
        } finally {
            try {
                conn.close();
            } catch (SQLException e) {
                // 记录日志，但通常不会有进一步的有效处理
            }
        }
    }
}
